// 3、写一个函数 向函数内传递3个文件的名字 file1 file2 file3
// 将file2 清空写入到 file1 （清空file1）
// 将file3 追加写入到 file1
#include <stdio.h>

void mergeFiles(const char *file1, const char *file2, const char *file3) {
    FILE *srcFile, *destFile;
    char buffer[1024];
    size_t bytesRead;

    // 清空 file2 并读取内容
    srcFile = fopen(file2, "w");
    if (srcFile == NULL) {
        perror("Failed to open file2");
        return;
    }

    // 打开 file1 并清空内容
    destFile = fopen(file1, "w");
    if (destFile == NULL) {
        perror("Failed to open file1");
        fclose(srcFile);
        return;
    }

    // 将 file2 的内容写入 file1
    while ((bytesRead = fread(buffer, 1, sizeof(buffer), srcFile)) > 0) {
        fwrite(buffer, 1, bytesRead, destFile);
    }

    // 关闭 file2 和 file1
    fclose(srcFile);
    fclose(destFile);

    // 打开 file3 并读取内容
    srcFile = fopen(file3, "r");
    if (srcFile == NULL) {
        perror("Failed to open file3");
        return;
    }

    // 以追加模式打开 file1
    destFile = fopen(file1, "a");
    if (destFile == NULL) {
        perror("Failed to open file1 in append mode");
        fclose(srcFile);
        return;
    }

    // 将 file3 的内容追加写入 file1
    while ((bytesRead = fread(buffer, 1, sizeof(buffer), srcFile)) > 0) {
        fwrite(buffer, 1, bytesRead, destFile);
    }

    // 关闭 file3 和 file1
    fclose(srcFile);
    fclose(destFile);
}

int main() {
    const char *file1 = "destination.txt";
    const char *file2 = "source1.txt";
    const char *file3 = "source2.txt";

    mergeFiles(file1, file2, file3);

    return 0;
}
